/*
 * Copyright 2012 zgnet.com All right reserved. This software is the
 * confidential and proprietary information of zgnet.com ("Confidential
 * Information"). You shall not disclose such Confidential Information and shall
 * use it only in accordance with the terms of the license agreement you entered
 * into with zgnet.com.
 */
package com.pshare.util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.pshare.constant.SeaxConstants;

public class CookieUtil {

    /**
     * 获取当前token.
     *
     * @return token
     */
    public static String getToken(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        String sid = "";
        if (cookies != null && cookies.length > 0) {
            for (Cookie sCookie : cookies) {
                if (sCookie.getName().equalsIgnoreCase(SeaxConstants.COOKIE_KEY)) {
                    sid = sCookie.getValue();
                }
            }
        }
        return sid;
    }

//    /**
//     * 获取用户姓名
//     *
//     * @param request
//     * @return
//     */
//    public static String getUserName(HttpServletRequest request) {
//        Cookie[] cookies = request.getCookies();
//        if (null != cookies) {
//            for (Cookie cookie : cookies) {
//                if (CookieConstants.COOKIE_USERINFO.equals(cookie.getName())) {
//                    String value = null;
//                    try {
//                        value = URLDecoder.decode(cookie.getValue(), "utf-8");
//                    } catch (UnsupportedEncodingException e) {
//                        // nothing
//                        return null;
//                    }
//                    return (value.split("\\|"))[0];
//                }
//            }
//        }
//        return null;
//    }

//    /**
//     * 获取用户组织信息
//     *
//     * @param request
//     * @return
//     */
//    public static String getOrgName(HttpServletRequest request) {
//        Cookie[] cookies = request.getCookies();
//        if (null != cookies) {
//            for (Cookie cookie : cookies) {
//                if (CookieConstants.COOKIE_USERINFO.equals(cookie.getName())) {
//                    String value = null;
//                    try {
//                        value = URLDecoder.decode(cookie.getValue(), "utf-8");
//                    } catch (UnsupportedEncodingException e) {
//                        // nothing
//                        return null;
//                    }
//                    return (value.split("\\|"))[1];
//                }
//            }
//        }
//        return null;
//    }

//    /**
//     * 移出天璇相关cookie
//     *
//     * @param request
//     * @param response
//     */
//    public static void removeUserLoginCookie(HttpServletRequest request,
//            HttpServletResponse response) {
//        Cookie[] cookies = request.getCookies();
//        if (cookies != null) {
//            for (int i = 0; i < cookies.length; i++) {
//                if (cookies[i].getName()
//                        .equals(CookieConstants.COOKIE_LOGIN_ID)) {// 移除Cookie中用户名
//                    removeCookie(response, cookies[i]);
//                } else if (cookies[i].getName().equals(
//                        CookieConstants.COOKIE_TOKEN)) {// 移除Cookie中Token.
//                    removeCookie(response, cookies[i]);
//                } else if (cookies[i].getName().equals(
//                        CookieConstants.COOKIE_USERINFO)) {// 移除Cookie中userinfo.
//                    removeCookie(response, cookies[i]);
//                }
//            }
//        }
//    }

//    /**
//     * 移出天璇相关cookie
//     *
//     * @param request
//     * @param response
//     */
//    public static void removeUserLoginCookie(HttpServletRequest request,
//            HttpServletResponse response,String domain) {
//        Cookie[] cookies = request.getCookies();
//        if (cookies != null) {
//            for (int i = 0; i < cookies.length; i++) {
//                    if (cookies[i].getName()
//                            .equals(CookieConstants.COOKIE_LOGIN_ID)) {// 移除Cookie中用户名
//                        removeCookie(response, cookies[i],domain);
//                    } else if (cookies[i].getName().equals(
//                            CookieConstants.COOKIE_TOKEN)) {// 移除Cookie中Token.
//                        removeCookie(response, cookies[i],domain);
//                    } else if (cookies[i].getName().equals(
//                            CookieConstants.COOKIE_USERINFO)) {// 移除Cookie中userinfo.
//                        removeCookie(response, cookies[i],domain);
//                    }
//            }
//        }
//    }

//    /**
//     * 移出cookie
//     *
//     * @param response
//     * @param key
//     */
//    public static void removeCookie(HttpServletResponse response, Cookie cookie) {
//        cookie.setValue(null);
//        cookie.setMaxAge(0);
//        cookie.setPath(CookieConstants.PATH);
//        cookie.setDomain(CookieConstants.DOMAIN_NAME);
//        cookie.setVersion(0);
//        response.addCookie(cookie);
//    }

//    /**
//     * 移出cookie
//     *
//     * @param response
//     * @param key
//     */
//    public static void removeCookie(HttpServletResponse response, Cookie cookie,String domain) {
//        cookie.setValue(null);
//        cookie.setMaxAge(0);
//        cookie.setPath(CookieConstants.PATH);
//        cookie.setDomain(domain);
//        cookie.setVersion(0);
//        response.addCookie(cookie);
//    }

//    public static void setUserLoginCookie(HttpServletResponse response,String cookiedomain,
//            String loginId) {
//        /**
//         * 把用户账号写入cookie
//         */
//        setCookie(response,cookiedomain, CookieConstants.COOKIE_LOGIN_ID,
//                  loginId, CookieConstants.COOKIE_TIMEOUT);
//
//        /**
//         * 把Token写入cookie
//         */
//        setCookie(response,cookiedomain, CookieConstants.COOKIE_TOKEN, MD5Util.generatePassword(CookieConstants.COOKE_LOGIN),-1);
//        
//        /**
//         * 把用户信息写入cookie
//         */
////        try {
////            setCookie(response, CookieConstants.COOKIE_USERINFO,
////                    URLEncoder.encode(userLogin.getUserInfo(), "utf-8"),
////                    userLogin.getCookieTimeout());
////        } catch (UnsupportedEncodingException e) {
////            throw new RuntimeException();
////        }
//    }

    /**
     * 写入cookie
     *
     * @param key
     * @param value
     * @param maxAge
     */
    public static void setCookie(HttpServletResponse response,String cookieDomain, String path, String key,
            String value, int maxAge) {
    	if (StringUtils.isBlank(value)) {
    		return;
    	}
        Cookie cookie = new Cookie(key, value);
        if (maxAge >= 0)
            cookie.setMaxAge(maxAge * 60 * 60 * 24);
        else
            cookie.setMaxAge(-1);
        cookie.setPath(path);
        if (StringUtils.isNotBlank(cookieDomain))
        	cookie.setDomain(cookieDomain);
        cookie.setVersion(0);
        response.addCookie(cookie);
    }

    
//    /**
//     * ȡ��cookieֵ
//     *
//     * @param key
//     */
//    public static String getCookie(HttpServletRequest request, String key) {
//    	Cookie[] cookies = request.getCookies();
//    	if(cookies==null || cookies.length ==0){
//    	    return null;
//    	}
//    	for (Cookie cookie : cookies) {
//			if(StringUtil.equals(cookie.getName(), key)){
//				return cookie.getValue();
//			}
//		}
//    	return null;
//    }

    
    
    /**
     * 获取客户端IP
     *
     * @param request
     * @return
     */
    public static String getIP(HttpServletRequest request) {
        String clientIp = null;
        String strClientIp = request.getHeader("x-forwarded-for");
        if (StringUtils.isBlank(strClientIp)
                || StringUtils.isEqualsIgnoreCase(strClientIp, "unknown")) {
            clientIp = request.getRemoteAddr();
        } else {
            String[] strIps = StringUtils.split(strClientIp, ",");  
            String strIp = null;
            for (int i = 0; i < strIps.length; i++) {
                strIp = strIps[i];
                if (!StringUtils.isEqualsIgnoreCase(strIp, "unknown")) {
                    clientIp = strIp;
                    break;
                }
            }
        }
        return clientIp;
    }

    /**
     * 对url中的参数进行�?��encode
     * @param url url为String类型
     * @param enc encode编码
     */
    public static String urlParamterEncode(String url, String enc) {
        int index = -1;
        if(StringUtils.isBlank(url) || StringUtils.isBlank(enc) || (index = url.indexOf("?")) < 0){
            return url;
        }
        // 截取requestUrl（包�??"�?
        StringBuffer requestString = new StringBuffer(url.substring(0, index + 1));
        String queryString = url.substring(index + 1);
        if(StringUtils.isBlank(queryString)){// 无参数直接返回requestUrl
            return url;
        }
        String[] paramterArray = queryString.split("&");// 参数切分
        try {
            for (String paramter : paramterArray) {
                if (StringUtils.isNotBlank(paramter) && paramter.indexOf("=") > 0) {
                    String key = paramter.split("=")[0];
                    String value = paramter.split("=").length >= 2 ? paramter.split("=")[1] : "";
                    // 参数拼接，value进行encode
                    if(StringUtils.isEmpty(value)){
                        requestString.append(key).append("=").append(value).append("&");
                    }else{
                        requestString.append(key).append("=").append(URLEncoder.encode(value, enc)).append("&");
                    }
                }else{
                    requestString.append(paramter).append("&");
                }
            }
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        requestString.deleteCharAt(requestString.length() - 1);// 删除�?���?��&
        return requestString.toString();
    }

    public static String urlParamterDecode(String url, String enc) {
        int index = -1;
        if(StringUtils.isBlank(url) || StringUtils.isBlank(enc) || (index = url.indexOf("?")) < 0){
            return url;
        }
        // 截取requestUrl（包�??"�?
        StringBuffer requestString = new StringBuffer(url.substring(0, index + 1));
        String queryString = url.substring(index + 1);
        if(StringUtils.isBlank(queryString)){// 无参数直接返回requestUrl
            return url;
        }
        String[] paramterArray = queryString.split("&");// 参数切分
        try {
            for (String paramter : paramterArray) {
                if (StringUtils.isNotBlank(paramter) && paramter.indexOf("=") > 0) {
                    String key = paramter.split("=")[0];
                    String value = paramter.split("=").length >= 2 ? paramter.split("=")[1] : "";
                    // 参数拼接，value进行decode
                    if(StringUtils.isEmpty(value)){
                        requestString.append(key).append("=").append(value).append("&");
                    }else{
                        requestString.append(key).append("=").append(URLDecoder.decode(value, enc)).append("&");
                    }
                }
            }
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        requestString.deleteCharAt(requestString.length() - 1);// 删除�?���?��&
        return requestString.toString();
    }
    
    
//    /**
//     * �����Ʒid �������ֿ�
//     * @param response
//     * @param cookieDomain
//     * @param id
//     */
//    public static void setUserBrowse(HttpServletRequest request,HttpServletResponse response,String cookieDomain ,String id){
//    	
//    	boolean isExists =false;
//    	JSONArray list = new JSONArray();
//    	if(CookieUtil.getCookie(request, CookieConstants.COOKIE_USERBROWSE)!=null){
//    		list=JSONArray.fromObject(CookieUtil.getCookie(request, CookieConstants.COOKIE_USERBROWSE));
//    	}
//    	for(int i=0;i<list.size();i++){
//    		String value = list.getString(i);
//    		if(StringUtils.isEqualsIgnoreCase(value, id)){
//    			isExists=true;
//    		}
//    	}
//    	if(!isExists){
//    		list.add(id);
//    		if(list.size()>10){
//        		int mol=list.size()%10;        		
//        			if(mol>0){
//        				list.remove(mol-1);
//        				list.add(mol-1, list.getString(list.size()-1));
//        				list.remove(list.size()-1);
//        			}else{
//        				list.remove(9);
//        				list.add(9, list.getString(list.size()-1));
//        				list.remove(list.size()-1);
//        			}   		
//        	}
//    	}    	
//    	setCookie(response, cookieDomain, CookieConstants.COOKIE_USERBROWSE, list.toString(), 25);
//    }
}
